package com.chatplus.application.aiprocessor.platform.image.chatgpt;

import cn.bugstack.openai.executor.model.chatgpt.config.ChatGPTConfig;
import cn.bugstack.openai.executor.parameter.*;
import cn.bugstack.openai.session.Configuration;
import cn.bugstack.openai.session.OpenAiSession;
import cn.bugstack.openai.session.defaults.DefaultOpenAiSessionFactory;
import com.chatplus.application.aiprocessor.interceptor.DynamicKeyHandleInterceptor;
import com.chatplus.application.aiprocessor.platform.image.ImgAiProcessorService;
import com.chatplus.application.aiprocessor.provider.ImgAiProcessorServiceProvider;
import com.chatplus.application.common.exception.BadRequestException;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.domain.dto.extend.ImgResultDto;
import com.chatplus.application.enumeration.AiPlatformEnum;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.stereotype.Service;

/**
 * ChatGPT 机器人画图处理器
 **/
@Service(value = ImgAiProcessorServiceProvider.SERVICE_NAME_PRE + "OPENAI")
public class ChatGPTImageProcessor extends ImgAiProcessorService {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(ChatGPTImageProcessor.class);

    public ImgResultDto process(Object prompt) {
        OpenAiSession openAiSession = getSessionFactory();
        try {
            ImageRequest request = ImageRequest.builder()
                    .prompt((String) prompt)
                    .channel(RequestChannel.OPEN_AI)
                    .model(ImageRequest.Model.DALL_E_3.getCode())
                    .size(ImageEnum.Size.size_1024.getCode())
                    .responseFormat(ImageEnum.ResponseFormat.B64_JSON.getCode())
                    .build();
            // 3. 应答请求

            ImageResponse imageResponse = null;
            if (openAiSession != null) {
                imageResponse = openAiSession.genImages(request);
            }
            if (imageResponse == null) {
                throw new BadRequestException("图片生成失败");
            }
            LOGGER.message("图片生成完成，上传中...").info();
            Item item = imageResponse.getData().getFirst();
            String openUrl = item.getUrl();
            String base64 = item.getB64Json();
            ImgResultDto imgResultDto = new ImgResultDto();
            imgResultDto.setUrl(saveToOss(openUrl, base64));
            imgResultDto.setRevisedPrompt(item.getRevisedPrompt());
            LOGGER.message("图片生成完成，上传完成...").context("imgResultDto", imgResultDto).info();
            return imgResultDto;
        } catch (Exception e) {
            LOGGER.message("图片生成失败").exception(e).error();
            throw new BadRequestException("图片生成失败");
        }
    }

    @Override
    public AiPlatformEnum getChannel() {
        return AiPlatformEnum.OPEN_AI;
    }

    @Override
    public synchronized OpenAiSession getSessionFactory() {
        instance();
        // 单独设置链接
        openApiKey.forEach(item -> {
            if (!item.getUrl().contains(ChatGPTConfig.V1_IMAGES_COMPLETIONS)) {
                item.setUrl(item.getUrl().concat(ChatGPTConfig.V1_IMAGES_COMPLETIONS));
            }
        });
        // 2. 配置文件
        Configuration configuration = new Configuration();
        configuration.setLevel(HttpLoggingInterceptor.Level.HEADERS);
        // 3. 会话工厂
        DefaultOpenAiSessionFactory factory = new DefaultOpenAiSessionFactory(configuration);
        factory.setInterceptor(new DynamicKeyHandleInterceptor(openApiKey, getChannel()));
        return factory.openSession();
    }
}
